﻿namespace Blaze.ConfigExporters
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using ConfigExportTool;
    using Configs;

    /// <summary>
    /// 屏蔽词导出。
    /// </summary>
    public class BadWordExporter : ExporterBase
    {
        /// <summary>
        /// 导出客户端配置。
        /// </summary>
        protected override void ExportForClient()
        {
            foreach (var db in mDBs)
                ExportToClient(db, "badword/" + db.Id);
        }

        /// <summary>
        /// 导出服务器配置。
        /// </summary>
        protected override void ExportForServer()
        {
            foreach (var db in mDBs)
                ExportToServer(db, "badword/" + db.Id);
        }

        /// <summary>
        /// 初始化。
        /// </summary>
        protected override void Initialize()
        {
            var dir = Path.Combine(Environment.CurrentDirectory, "../../Configs/屏蔽词");
            var dbs = new List<BadWordDB>();
            foreach (var path in Directory.GetFiles(dir, "*.txt"))
            {
                var dbName = Path.GetFileNameWithoutExtension(path);
                var db = new BadWordDB
                {
                    Id = dbName,
                    Data = new BadWordDB.DFANode()
                };
                foreach (var line in File.ReadAllLines(path))
                    append(db, line);
                dbs.Add(db);
            }
            mDBs = dbs.ToArray();
        }

        private static void append(BadWordDB db, string text)
        {
            var node = db.Data;
            for (var index = 0; index < text.Length; index++)
            {
                var c = text[index];
                var code = c;
                var isFound = false;
                if (node.Nodes == null)
                    node.Nodes = new List<BadWordDB.DFANode>();
                foreach (var n in node.Nodes.ToArray())
                {
                    if (n.Key == code)
                    {
                        node = n;
                        isFound = true;
                        break;
                    }
                }
                if (!isFound)
                {
                    var newNode = new BadWordDB.DFANode
                    {
                        End = false,
                        Key = code,
                        Debug = Convert.ToString(c),
                    };
                    node.Nodes.Add(newNode);
                    node = newNode;
                }
                if (index == text.Length - 1)
                    node.End = true;
            }
        }

        private BadWordDB[] mDBs;
    }
}